using B.S.RbacData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Write.API.Applications.Commands.suppliers;

namespace SupplierCustomerManagement.Write.API.Applications.CommandHandlters.suppliers
{
    /// <summary>
    /// 逻辑删除供应商命令处理器
    /// </summary>
    public class DeleteSupplierCommandHandler : IRequestHandler<DeleteSupplierCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<Supplier> _supplierRepository;
        private readonly ILogger<DeleteSupplierCommandHandler> _logger;

        public DeleteSupplierCommandHandler(
            IBaseRepository<Supplier> supplierRepository,
            ILogger<DeleteSupplierCommandHandler> logger)
        {
            _supplierRepository = supplierRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理逻辑删除供应商命令
        /// </summary>
        /// <param name="request">删除供应商命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<bool>> Handle(DeleteSupplierCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始逻辑删除供应商，ID: {SupplierId}", request.Id);

                // 检查供应商是否存在且未被删除
                var existingSupplier = await _supplierRepository.GetAll()
                    .FirstOrDefaultAsync(s => s.Id == request.Id && !s.IsDeleted, cancellationToken);

                if (existingSupplier == null)
                {
                    _logger.LogWarning("供应商不存在或已被删除，ID: {SupplierId}", request.Id);
                    return ApiResult<bool>.Error("供应商不存在或已被删除");
                }

                // 检查供应商状态，如果为启用状态则不允许删除
                if (existingSupplier.Status == "启用")
                {
                    _logger.LogWarning("无法删除启用状态的供应商，ID: {SupplierId}, 名称: {SupplierName}, 状态: {Status}", 
                        request.Id, existingSupplier.SupplierName, existingSupplier.Status);
                    return ApiResult<bool>.Error("无法删除启用状态的供应商，请先停用后再删除");
                }

                // 执行逻辑删除（软删除）
                existingSupplier.IsDeleted = true;
                existingSupplier.UpdatedTime = DateTime.Now;
                existingSupplier.UpdatedBy = 1;

              
                // 执行更新操作
                var result = await _supplierRepository.UpdateAsync(existingSupplier);

                if (result > 0)
                {
                    _logger.LogInformation("成功逻辑删除供应商，ID: {SupplierId}, 名称: {SupplierName}", 
                        request.Id, existingSupplier.SupplierName);
                    
                    return ApiResult<bool>.Success(true, "供应商删除成功");
                }
                else
                {
                    _logger.LogError("逻辑删除供应商失败，ID: {SupplierId}, 名称: {SupplierName}", 
                        request.Id, existingSupplier.SupplierName);
                    
                    return ApiResult<bool>.Error("供应商删除失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "逻辑删除供应商时发生异常，ID: {SupplierId}", request.Id);
                
                return ApiResult<bool>.Error($"删除供应商时发生异常: {ex.Message}");
            }
        }
    }
} 